package com.newhero.product.module.sys.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.newhero.product.common.mybatis.mapper.EntityWrapper;
import com.newhero.product.common.service.impl.BaseServiceImpl;
import com.newhero.product.module.sys.mapper.OrganMapper;
import com.newhero.product.module.sys.model.Organ;
import com.newhero.product.module.sys.service.IOrganService;

@Service
public class OrganServiceImpl extends BaseServiceImpl<OrganMapper, Organ>
		implements IOrganService {

	/**
	 * 递归办法
	 * 
	 * @param organID
	 * @param idList
	 */
	private void genIDListByOrganID(String organID, List<String> idList) {
		Map<String, Object> columnMap2 = new HashMap<String, Object>();
		columnMap2.put("organID", organID);
		List<Organ> organList2 = selectByMap(columnMap2);
		for (Organ a : organList2) {
			String id = a.getOrganID();
			idList.add(id);
			genIDListByOrganID(id, idList);
		}
	}

	@Override
	public List<String> getIDListByOrganID(String organID) {
		/**
		 * 由于各种数据库兼容性问题，就不用SQL查了，用程序查
		 */
		List<String> idList = new ArrayList<String>();
		idList.add(organID);
		genIDListByOrganID(organID, idList);
		return idList;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newhero.product.module.sys.service.IOrganService#recursionOrganList
	 * (java.lang.String)
	 */
	@Override
	public List<Organ> recursionOrganList(String organID) {
		List<Organ> resultList = new ArrayList<Organ>();
		Organ organ = this.selectById(organID);
		resultList.add(organ);
		genOrganChildren(resultList, organ);
		Collections.sort(resultList, new Comparator<Organ>() {
			@Override
			public int compare(Organ o1, Organ o2) {
				return o1.getOrganOrder() - o2.getOrganOrder();
			}
		});
		return resultList;
	}

	private void genOrganChildren(List<Organ> resultList, Organ organ) {
		EntityWrapper<Organ> wrapper = new EntityWrapper<Organ>();
		wrapper.eq("organPID", organ.getOrganID());
		List<Organ> organList = selectList(wrapper);
		for (Organ so : organList) {
			resultList.add(so);
			EntityWrapper<Organ> wr = new EntityWrapper<Organ>();
			wrapper.eq("organPID", so.getOrganID());
			List<Organ> childrenList = selectList(wr);
			if (childrenList != null && childrenList.size() > 0) {
				genOrganChildren(resultList, so);
			}
		}

	}
}
